package com.lc.ei.config.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson2.JSON;
import com.lc.ei.utils.ExcelUtil;
import com.study.common.utils.AliTranslateUtil;
import com.study.common.utils.LcStrUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description: Excel文件监听器，由于加入了翻译的逻辑，监听器处理数据时间会比较久，
 * 具体体现在【EasyExcel.read(file.getInputStream(), excelListener).sheet().doRead();】执行时间长
 * @author: LChuang
 * @date: 2023/9/18 10:25
 */
@Slf4j
@Data
@Component
@EqualsAndHashCode(callSuper = true)
public class ExcelListener extends AnalysisEventListener<Map<Integer, String>> {

    // 文件传入后的Excel数据，excel列索引对应值
    private List<Map<Integer, Map<Integer, String>>> dataList;

    // 操作后的Excel数据，用列名对应值
    private Map<Integer, Map<String, String>> modifyDataMap;

    // Excel表头
    private Map<Integer, String> headTitleMap = new HashMap<>();

    // 英文Excel表头
    private List<String> modifyHeadList;

    public ExcelListener() {
        dataList = new ArrayList<>();
    }

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        Map<Integer, Map<Integer, String>> map = new HashMap<>();
        map.put(context.readRowHolder().getRowIndex(), data);
        dataList.add(map);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        long start = System.currentTimeMillis();
        modifyDataMap = ExcelUtil.handleData(dataList, headTitleMap);
        long end = System.currentTimeMillis();
        log.info("数据解析+翻译已完成，共：{} 条数据，用时：{} s", context.getTotalCount(), (end - start) / 1000);
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        long start = System.currentTimeMillis();
        // 翻译表头数据
        headTitleMap = ExcelUtil.handleTitle(headMap);
        modifyHeadList = new ArrayList<>(headTitleMap.values());
        long end = System.currentTimeMillis();
        log.info("翻译表头执行完毕，总共：{} 条，用时：{} s", headTitleMap.size(), (end - start) / 1000);
    }
}
